//
//  LiveUIParView.m
//  TILLiveSDKShow
//
//  Created by wilderliao on 16/11/9.
//  Copyright © 2016年 Tencent. All rights reserved.
//

#import "LiveUIParView.h"





@interface LiveUIParView () <ILiveSpeedTestDelegate>
{
    UInt64  _channelId;
}
@end

UIAlertController *_alert;

@implementation LiveUIParView

- (void)configWith:(LiveUIParViewConfig *)config
{
    _config = config;
    [self addAVParamSubViews];
    _resolutionDic = [NSMutableDictionary dictionary];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onParPure:) name:kPureDelete_Notification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onParNoPure:) name:kNoPureDelete_Notification object:nil];
    [ILiveSpeedTestManager shareInstance].delegate = self;
}

- (void)onParPure:(NSNotification *)noti
{
    CGRect selfFrame = self.frame;
    _restoreRect = selfFrame;
    [UIView animateWithDuration:0.5 animations:^{
        CGRect moveToRect = CGRectMake(selfFrame.origin.x, -(selfFrame.origin.y+selfFrame.size.height), selfFrame.size.width, selfFrame.size.height);
        [self setFrame:moveToRect];
    } completion:^(BOOL finished) {
        self.hidden = YES;
    }];
}

- (void)onParNoPure:(NSNotification *)noti
{
    self.hidden = NO;
    [UIView animateWithDuration:0.5 animations:^{
        [self setFrame:_restoreRect];
    } completion:^(BOOL finished) {
    }];
}

- (void)addAVParamSubViews
{
    _funs = [NSMutableArray array];
    //AV Param View
    if (_config.isHost)
    {
        _interactBtn = [[UIButton alloc] init];
        [_interactBtn setImage:[UIImage imageNamed:@"interactive"] forState:UIControlStateNormal];
        [_interactBtn addTarget:self action:@selector(onInteract:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_interactBtn];
        [_funs addObject:_interactBtn];
    }
    
    
    [_funs addObject:_parBtn];
    
    
    if (_config.isHost)
    {
        _linkRoomBtn = [[UIButton alloc] init];
        [_linkRoomBtn setTitle:@"串 门" forState:UIControlStateNormal];
        [_linkRoomBtn addTarget:self action:@selector(onLinkRoomAction) forControlEvents:UIControlEventTouchUpInside];
        
        
        
        
        _linkRoomBtn.layer.cornerRadius = 4;
        _linkRoomBtn.layer.masksToBounds = YES;
        [self addSubview:_linkRoomBtn];
        [_funs addObject:_linkRoomBtn];
        
        _unlinkRoomBtn = [[UIButton alloc] init];
        [_unlinkRoomBtn setTitle:@"取消串门" forState:UIControlStateNormal];
        [_unlinkRoomBtn addTarget:self action:@selector(onUnLinkRoomAction) forControlEvents:UIControlEventTouchUpInside];
        
        
        
        
        _unlinkRoomBtn.layer.cornerRadius = 4;
        _unlinkRoomBtn.layer.masksToBounds = YES;
        [self addSubview:_unlinkRoomBtn];
        [_funs addObject:_unlinkRoomBtn];
    }
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    CGRect rect = self.bounds;
    int maxColumn = 5;
    NSInteger width = (rect.size.width - (maxColumn + 1)*3) / maxColumn;
    if (width > 80)
    {
        width = 80;
    }
    CGFloat marginX = 3;
    if (_funs.count < 5)//按钮较少时，靠右对齐
    {
        int magin = ((5 - (int)_funs.count) + 1)*3 + (5 - (int)_funs.count)*(int)width;
        rect.origin.x += magin;
    }
    
}

- (void)onInteract:(UIButton *)button
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(onInteract)])
    {
        [self.delegate onInteract];
    }
}

- (void)onPar:(UIButton *)button
{
    if (!button.selected)
    {
        __weak typeof(self) ws = self;
        
        ws.paramTextView = [[UITextView alloc] init];
        CGRect selfRect = self.frame;
        ws.paramTextView.editable = NO;
        
        
        [ws.paramTextView setFrame:CGRectMake(0, selfRect.origin.y+selfRect.size.height+8, selfRect.size.width, 350)];
        [self.superview addSubview:ws.paramTextView];
        _logTimer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(onLogTimer) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_logTimer forMode:NSDefaultRunLoopMode];
    }
    else
    {
        if (_paramTextView)
        {
            [_paramTextView removeFromSuperview];
        }
        [_logTimer invalidate];
        _logTimer = nil;
    }
    button.selected = !button.selected;
}

- (void)onLogTimer
{
    __weak typeof(self) ws = self;
    QAVContext *context = [[ILiveSDK getInstance] getAVContext];
    if (context.videoCtrl && context.audioCtrl && context.room)
    {
        ILiveQualityData *qualityData = [[ILiveRoomManager getInstance] getQualityData];
        NSMutableString *paramString = [NSMutableString string];
        //FPS
        [paramString appendString:[NSString stringWithFormat:@"FPS:%ld.\n",qualityData.interactiveSceneFPS/10]];
        //Send Recv
        [paramString appendString:[NSString stringWithFormat:@"Send: %ldkbps, Recv: %ldkbps.\n",qualityData.sendRate,(long)qualityData.recvRate]];
        //sendLossRate recvLossRate
        CGFloat sendLossRate = (CGFloat)qualityData.sendLossRate / (CGFloat)100;
        CGFloat recvLossRate = (CGFloat)qualityData.recvLossRate / (CGFloat)100;
        NSString *per = @"%";
        [paramString appendString:[NSString stringWithFormat:@"SendLossRate: %.2f%@,   RecvLossRate: %.2f%@.\n",sendLossRate,per,recvLossRate,per]];
        
        //appcpu syscpu
        CGFloat appCpuRate = (CGFloat)qualityData.appCPURate / (CGFloat)100;
        CGFloat sysCpuRate = (CGFloat)qualityData.sysCPURate / (CGFloat)100;
        [paramString appendString:[NSString stringWithFormat:@"AppCPURate:   %.2f%@,   SysCPURate:   %.2f%@.\n",appCpuRate,per,sysCpuRate,per]];
        
        //分别角色的分辨率
        NSArray *keys = [_resolutionDic allKeys];
        for (NSString *key in keys)
        {
            QAVFrameDesc *desc = _resolutionDic[key];
            [paramString appendString:[NSString stringWithFormat:@"%@---> %d * %d\n",key,desc.width,desc.height]];
        }
        //avsdk版本号
        NSString *avSDKVer = [NSString stringWithFormat:@"AVSDK版本号: %@\n",[QAVContext getVersion]];
        [paramString appendString:avSDKVer];
        //房间号
        int roomid = [[ILiveRoomManager getInstance] getRoomId];
        [paramString appendString:[NSString stringWithFormat:@"房间号:%d\n",roomid]];
        //角色
        NSString *roleStr = _config.isHost ? @"主播" : @"非主播";
        [paramString appendString:[NSString stringWithFormat:@"角色:%@\n",roleStr]];
        
        //采集信息
        NSString *videoParam = [context.videoCtrl getQualityTips];
        NSArray *array = [videoParam componentsSeparatedByString:@"\n"]; //从字符A中分隔成2个元素的数组
        if (array.count > 3)
        {
            NSString *resolution = [array objectAtIndex:2];
            [paramString appendString:[NSString stringWithFormat:@"%@\n",resolution]];
        }
        //麦克风
        NSString *isOpen = [[ILiveRoomManager getInstance] getCurMicState] ? @"ON" : @"OFF";
        [paramString appendString:[NSString stringWithFormat:@"麦克风: %@\n",isOpen]];
        //扬声器
        NSString *isOpenSpeaker = [[ILiveRoomManager getInstance] getCurSpeakerState] ? @"ON" : @"OFF";
        [paramString appendString:[NSString stringWithFormat:@"扬声器: %@\n",isOpenSpeaker]];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            ws.paramTextView.text = paramString;
        });
    }
}

- (void)onPush:(UIButton *)button
{
    
    
    
}

- (void)pushStream:(UIButton *)button encodeType:(AVEncodeType)encodeType recordType:(AVRecordFileType)recordType
{
  
}

- (void)shareLive:(NSString *)url
{
   }


- (void)setChannelId:(UInt64)channelId
{
    _channelId = channelId;
}

- (void)onRecord:(UIButton *)button
{
    button.selected = !button.selected;
  
}



- (void)removeSelfAndLinked:(NSMutableArray *)array
{

}


- (void)startRecord:(UIButton *)button type:(AVRecordType)recordType
{

}

- (void)onTestSpeed:(UIButton *)button
{
    SpeedTestRequestParam *param = [[SpeedTestRequestParam alloc] init];
    [[ILiveSpeedTestManager shareInstance] requestSpeedTest:param succ:^{
        
    } fail:^(NSString *module, int errId, NSString *errMsg) {
        

    }];
}




- (NSString *)ip4FromUInt:(unsigned int)ipNumber
{
    if (sizeof (unsigned int) != 4)
    {
        NSLog(@"Unkown type!");
        return @"";
    }
    unsigned int mask = 0xFF000000;
    unsigned int array[sizeof(unsigned int)];
    int steps = 8;
    int counter;
    for (counter = 0; counter < 4 ; counter++)
    {
        array[counter] = ((ipNumber & mask) >> (32-steps*(counter+1)));
        mask >>= steps;
    }
    NSMutableString *mutableString = [NSMutableString string];
    for (int index = counter-1; index >=0; index--)
    {
        [mutableString appendString:[NSString stringWithFormat:@"%d",array[index]]];
        if (index != 0)
        {
            [mutableString appendString:@"."];
        }
    }
    
    return mutableString;
}
@end

@implementation LiveUIParViewConfig
@end
